import React, { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Breadcrumb } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import PostEditor from '../../components/PostEditor/PostEditor';
import type { CreatePostParams } from '../../types';
import './CreatePost.scss';

const CreatePost: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // 从路径中提取类型
  const pathParts = location.pathname.split('/');
  const category = pathParts[2] as 'discussion' | 'help' | 'share' | 'trade'; // posts/[type]/create

  // 验证类型
  useEffect(() => {
    if (!['discussion', 'help', 'share', 'trade'].includes(category)) {
      navigate('/');
    }
  }, [category, navigate]);

  if (!['discussion', 'help', 'share', 'trade'].includes(category)) {
    return null;
  }

  // 处理提交
  const handleSubmit = async (values: CreatePostParams) => {
    console.log('提交的帖子数据:', values);
    
    // 调用API提交数据
    // TODO: 取消注释以使用真实API
    // import { createPost } from '../../api/post';
    // await createPost(values);
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 提交成功后跳转到对应的列表页
    const routes = {
      discussion: '/posts/discussion',
      help: '/posts/help',
      share: '/posts/share',
      trade: '/posts/trade',
    };
    
    navigate(routes[category]);
  };

  // 处理取消
  const handleCancel = () => {
    navigate(-1);
  };

  // 面包屑配置
  const breadcrumbConfig = {
    discussion: { label: '讨论区', path: '/posts/discussion' },
    help: { label: '求助区', path: '/posts/help' },
    share: { label: '分享区', path: '/posts/share' },
    trade: { label: '交易区', path: '/posts/trade' },
  };

  const currentConfig = breadcrumbConfig[category];

  return (
    <div className="create-post-page">
      <div className="breadcrumb-wrapper">
        <Breadcrumb
          items={[
            {
              href: '/',
              title: <HomeOutlined />,
            },
            {
              href: currentConfig.path,
              title: currentConfig.label,
            },
            {
              title: '发布',
            },
          ]}
        />
      </div>

      <PostEditor
        category={category}
        onSubmit={handleSubmit}
        onCancel={handleCancel}
      />
    </div>
  );
};

export default CreatePost;

